package com.glkj.vipsystem.modules.app.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.glkj.vipsystem.common.exception.BizException;
import com.glkj.vipsystem.common.utils.Constant;
import com.glkj.vipsystem.common.utils.PageUtils;
import com.glkj.vipsystem.entity.ao.*;
import com.glkj.vipsystem.modules.ServiceResult;
import com.glkj.vipsystem.modules.app.annotation.LoginIgnore;
import com.glkj.vipsystem.modules.app.annotation.LoginUser;
import com.glkj.vipsystem.modules.app.form.BaseForm;
import com.glkj.vipsystem.modules.app.utils.JwtUtils;
import com.glkj.vipsystem.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(tags = "商家端API")
@RestController
@RequestMapping("/api/merchant")
public class AppMerchantController extends AbstractAppController {
    @Resource
    private IVipCardService vipCardService;
    @Resource
    private IOrderService orderService;
    @Resource
    private ICompanyService companyService;
    @Resource
    private IEmployeeService employeeService;
    @Resource
    private IShopService shopService;
    @Resource
    private IVipCardRecordService vipCardRecordService;

    @ApiOperation(value = "获取公司信息")
    @GetMapping("/company")
    public ServiceResult<CompanyAO> company(@ApiIgnore @LoginUser MemberAO member) {
        String mobile = member.getMobile();
        CompanyAO companyAO = companyService.selectOne(
                new EntityWrapper<CompanyAO>()
                        .eq("manager_mobile", mobile)
        );
        if(companyAO != null){
            companyAO.setUsername(null);
            return ServiceResult.ok(companyAO);
        }
        EmployeeAO employeeAO = employeeService.selectOne(
                new EntityWrapper<EmployeeAO>()
                        .eq("employee_mobile", mobile)
        );
        if(employeeAO == null){
            return ServiceResult.error(999,"无权限");
        }
        companyAO = companyService.selectById(employeeAO.getCompanyId());
        if (companyAO != null){
            companyAO.setUsername(null);
            return ServiceResult.ok(companyAO);
        }
        return ServiceResult.error(999,"无权限");
    }

    @ApiOperation(value = "账号下的店铺列表")
    @GetMapping("/shop/list")
    public ServiceResult<List<ShopAO>> vipCardList(@ApiIgnore @LoginUser MemberAO member) {
        String mobile = member.getMobile();
        Wrapper<ShopAO> wrapper = new EntityWrapper<>();
        wrapper.orderBy("id desc");
        CompanyAO companyAO = companyService.selectOne(
                new EntityWrapper<CompanyAO>()
                        .eq("manager_mobile", mobile)
        );
        EmployeeAO employeeAO = employeeService.selectOne(
                new EntityWrapper<EmployeeAO>()
                        .eq("employee_mobile", mobile)
        );
        if (companyAO != null) {
            wrapper.eq("company_id", companyAO.getId());
        } else if (employeeAO != null) {
            wrapper.eq("id", employeeAO.getShopId());
        } else {
            return ServiceResult.error(999, "无权限");
        }
        List<ShopAO> list = shopService.selectList(wrapper);
        return ServiceResult.ok(list);
    }

    @ApiOperation(value = "收银记录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "time", value = "时间范围:格式：yyyy-MM-dd~yyyy-MM-dd", paramType = "query", dataType = "string", required = true),
            @ApiImplicitParam(name = "shopId", value = "店铺id", paramType = "query", dataType = "int", required = true)

    })
    @GetMapping("/cash/record")
    public ServiceResult<PageUtils> cashRecord(BaseForm form, String time, Integer shopId) {
        validRole();
        if (StringUtils.isBlank(time) || !time.contains("~")) {
            return ServiceResult.error("请正确选择时间范围");
        }
        if (shopId == null) {
            return ServiceResult.error("请选择要查看的店铺");
        }
        String[] timeRange = time.split("~");
        Page<OrderAO> page = orderService.selectPage(
                new Page<>(form.getPage(), form.getPageSize()),
                new EntityWrapper<OrderAO>()
                        .orderBy("id desc")
                        .ge("create_time", timeRange[0].trim()).le("create_time", timeRange[1].trim() + " 23:59:59")
                        .eq("shop_id", shopId)
        );
        return ServiceResult.ok(new PageUtils(page));
    }


    @ApiOperation(value = "营收统计")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "time", value = "时间范围:格式：yyyy-MM-dd~yyyy-MM-dd", paramType = "query", dataType = "string", required = true),
            @ApiImplicitParam(name = "shopId", value = "店铺id", paramType = "query", dataType = "int", required = true)

    })
    @GetMapping("/revenue/data")
    public ServiceResult<Map<String, Object>> revenueData(Integer shopId, String time) {
        validRole();
        if (StringUtils.isBlank(time) || !time.contains("~")) {
            return ServiceResult.error("请正确选择时间范围");
        }
        if (shopId == null) {
            return ServiceResult.error("请选择要查看的店铺");
        }
        String[] timeRange = time.split("~");
        String startTime = timeRange[0].trim();
        String endTime = timeRange[1].trim() + " 23:59:59";
        Map<String, Object> data = new HashMap<>();

        // 查询 散客收银人次、金额
        Map<String, Object> sankeData = orderService.selectMap(
                new EntityWrapper<OrderAO>()
                        .setSqlSelect("count(*) as num,sum(order_amount) as amount")
                        .between("create_time", startTime, endTime)
                        .eq("shop_id", shopId)
                        .isNull("vip_card_id")
        );
        if (sankeData == null) {
            sankeData = new HashMap<>();
        }
        sankeData.putIfAbsent("num", 0);
        sankeData.putIfAbsent("amount", 0);

        // 查询 新办会员人次、金额
        Map<String, Object> vipCardData = vipCardService.selectMap(
                new EntityWrapper<VipCardAO>()
                        .setSqlSelect("count(*) as num,sum(card_fee) as amount")
                        .between("create_time", startTime, endTime)
                        .eq("shop_id", shopId)
        );
        if (vipCardData == null) {
            vipCardData = new HashMap<>();
        }
        vipCardData.putIfAbsent("num", 0);
        vipCardData.putIfAbsent("amount", 0);

        // 查询 会员消费人次、金额
        Map<String, Object> consumeData = orderService.selectMap(
                new EntityWrapper<OrderAO>()
                        .setSqlSelect("count(*) as num,sum(order_amount) as amount")
                        .between("create_time", startTime, endTime)
                        .eq("shop_id", shopId)
                        .isNotNull("vip_card_id")
        );
        if (consumeData == null) {
            consumeData = new HashMap<>();
        }
        consumeData.putIfAbsent("num", 0);
        consumeData.putIfAbsent("amount", 0);

        data.put("sankeData", sankeData);
        data.put("vipCardData", vipCardData);
        data.put("consumeData", consumeData);

        return ServiceResult.ok(data);
    }


    @ApiOperation(value = "会员新增")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "time", value = "时间范围:格式：yyyy-MM-dd~yyyy-MM-dd", paramType = "query", dataType = "string", required = true),
            @ApiImplicitParam(name = "shopId", value = "店铺id", paramType = "query", dataType = "int", required = true)

    })
    @GetMapping("/vipCard/data")
    public ServiceResult<Object> vipCardData(Integer shopId, String time) {
        validRole();
        if (StringUtils.isBlank(time) || !time.contains("~")) {
            return ServiceResult.error("请正确选择时间范围");
        }
        if (shopId == null) {
            return ServiceResult.error("请选择要查看的店铺");
        }
        String[] timeRange = time.split("~");
        String startTime = timeRange[0].trim();
        String endTime = timeRange[1].trim() + " 23:59:59";
        Map<String, Object> data = new HashMap<>();

        // 查询会员卡开卡次数
        Map<String, Object> newData = vipCardService.selectMap(
                new EntityWrapper<VipCardAO>()
                        .setSqlSelect("COUNT( CASE WHEN card_type = 1 THEN 1 ELSE NULL END ) AS cika," +
                                "COUNT( CASE WHEN card_type = 2 THEN 1 ELSE NULL END ) AS chongzhika," +
                                "COUNT( CASE WHEN card_type = 3 THEN 1 ELSE NULL END ) AS jifenka")
                        .between("create_time", startTime, endTime)
                        .eq("shop_id", shopId)
        );
        if (newData == null) {
            newData = new HashMap<>();
        }
        newData.putIfAbsent("cika", 0);
        newData.putIfAbsent("chongzhika", 0);
        newData.putIfAbsent("jifenka", 0);
        data.put("newData", newData);

        // 查询续费充值人次
        Map<String, Object> chargeData = vipCardRecordService.selectMap(
                new EntityWrapper<VipCardRecordAO>()
                        .setSqlSelect("COUNT( CASE WHEN card_type = 1 THEN 1 ELSE NULL END ) AS cika," +
                                "COUNT( CASE WHEN card_type = 2 THEN 1 ELSE NULL END ) AS chongzhika," +
                                "COUNT( CASE WHEN card_type = 3 THEN 1 ELSE NULL END ) AS jifenka")
                        .eq("change_type", Constant.VipCardRecordChangeType.SYSTEM.getValue())
                        .between("create_time", startTime, endTime)
                        .eq("shop_id", shopId)
        );
        if (chargeData == null) {
            chargeData = new HashMap<>();
        }
        chargeData.putIfAbsent("cika", 0);
        chargeData.putIfAbsent("chongzhika", 0);
        chargeData.putIfAbsent("jifenka", 0);
        data.put("chargeData", chargeData);

        return ServiceResult.ok(data);
    }

}
